import { useState, useEffect } from 'react';
import { message } from 'antd';

export default (request: any, pagination: any, params: any) => {
  const { api = '', requestType = 'POST' } = request;
  console.log('fn', 'pagination', pagination, 'value', params);
  if (!api) {
    return {
      data: {
        total: 0,
        dataSource: [],
      },
      loading: false,
    };
  }

  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<any[]>([]);

  useEffect(() => {
    let lastParams: any = {};
    if (requestType === 'GET') {
      lastParams = { query: { ...pagination, ...params } };
    } else if (requestType === 'POST') {
      lastParams = { body: { ...pagination, ...params } };
    }

    setLoading(true);
    api({ ...lastParams })
      .then((res: anyObject) => {
        setLoading(false);
        if (res.code !== 0) {
          message.warning(res.msg);
          setTotal(0);
          setDataSource([]);
          return;
        } else {
          setTotal(res?.data?.total || res?.data?.count || 0);
          setDataSource(res.data.list || res?.data?.content || []);
        }
      })
      .catch((err: any) => {
        setTotal(0);
        setDataSource([]);
        setLoading(false);
        message.warning(err.msg);
      });
    // eslint-disable-next-line
  }, [pagination]);

  return {
    total,
    loading,
    dataSource,
  };
};
